package jwt

import (
	"github.com/golang-jwt/jwt/v4"
	"time"
)

var jwtSecret = []byte("FanOne")

type Claims struct {
	Username string `json:"username"`
	jwt.Claims
}

func GenerateToken(username string) (string, error) {
	nowTime := time.Now()
	expireTime := nowTime.Add(3 * time.Hour)

	claims := Claims{
		Username: username,
		Claims:jwt.RegisteredClaims{
			ExpiresAt: &jwt.NumericDate{Time: expireTime},
			Issuer: "mall",

		},
	}
	// 加密并获得完整的编码后的字符串token
	accessToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(jwtSecret)
	if err != nil {
		return "", err
	}
	return accessToken, err
}


// ParseToken 验证用户token
func ParseToken(token string) (*Claims,error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})
	if tokenClaims != nil{
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	return nil, err
}